package com.bndg.blackjack

import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.SystemClock
import android.util.Log
import android.widget.Toast
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.util.UUID

/**
 * @author r
 * @date 2024/12/5
 * @description Brief description of the file content.
 */
object AppUtils {

    /** 数组的长度为2代表只记录双击操作  */
    val TIME_ARRAY: LongArray = LongArray(2)
    val gson: Gson = Gson()
    var application: Application? = null

    /**
     * 是否在短时间内进行了双击操作
     */
    fun isOnDoubleClick(): Boolean {
        // 默认间隔时长
        return isOnDoubleClick(1500)
    }

    /**
     * 是否在短时间内进行了双击操作
     */
    fun isFastDoubleClick(): Boolean {
        // 默认间隔时长
        return isOnDoubleClick(500)
    }

    /**
     * 是否在短时间内进行了双击操作
     */
    fun isOnDoubleClick(time: Int): Boolean {
        System.arraycopy(TIME_ARRAY, 1, TIME_ARRAY, 0, TIME_ARRAY.size - 1)
        TIME_ARRAY[TIME_ARRAY.size - 1] = SystemClock.uptimeMillis()
        return TIME_ARRAY[0] >= (SystemClock.uptimeMillis() - time)
    }

    fun dp2px(dpValue: Float): Int {
        val scale = Resources.getSystem().displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    fun sp2px(spValue: Float): Int {
        val fontScale = Resources.getSystem().displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }

    fun px2sp(pxValue: Float): Int {
        val fontScale = Resources.getSystem().displayMetrics.scaledDensity
        return (pxValue / fontScale + 0.5f).toInt()
    }

    /**
     * 将 JSON 字符串反序列化为指定类型对象
     */
    fun <T> deserializeByJson(data: String, clazz: Class<T>): T? {
        return try {
            gson.fromJson(data, clazz)
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 将对象序列化为 JSON 字符串
     */
    fun <T> serializeToJson(t: T): String {
        return gson.toJson(t)
    }

    fun show(s: String) {
        GlobalScope.launch(Dispatchers.Main){
            application?.let {
                Toast.makeText(it, s, Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun put(key: String, value: String) {
        val sp = application?.getSharedPreferences("blackjack", Context.MODE_PRIVATE)
        sp?.edit()?.putString(key, value)?.apply()
    }

    fun get(key: String): String? {
        val sp = application?.getSharedPreferences("blackjack", Context.MODE_PRIVATE)
        return sp?.getString(key, null)
    }

    fun generateId(): String {
        return UUID.randomUUID().toString().replace("-".toRegex(), "")
    }

    fun getLocalIpAddress(context: Context): String {
        try {
            // 获取系统的 ConnectivityManager
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            // 获取当前网络连接
            val activeNetwork: Network = connectivityManager.activeNetwork ?: return "No network connection"
            val networkCapabilities: NetworkCapabilities =
                connectivityManager.getNetworkCapabilities(activeNetwork) ?: return "No network capabilities"

            // 判断网络类型
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                // 如果是 Wi-Fi 网络，直接获取 Wi-Fi 的 IP 地址
                val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                val wifiInfo: WifiInfo = wifiManager.connectionInfo
                val ipAddress = wifiInfo.ipAddress
                return formatIpAddress(ipAddress)
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                // 如果是蜂窝网络（移动数据），通过网络接口获取 IP 地址
                return getIpAddressFromNetworkInterfaces()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }

        return ""
    }

    // 格式化 IP 地址为标准的 IPv4 格式
    fun formatIpAddress(ipAddress: Int): String {
        return String.format(
            "%d.%d.%d.%d",
            (ipAddress and 0xFF),
            (ipAddress shr 8 and 0xFF),
            (ipAddress shr 16 and 0xFF),
            (ipAddress shr 24 and 0xFF)
        )
    }

    // 从所有网络接口中获取 IP 地址
    fun getIpAddressFromNetworkInterfaces(): String {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    // 排除回环地址，确保是 IPv4 地址
                    if (!address.isLoopbackAddress && address is Inet4Address) {
                        return address.hostAddress
                    }
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        return ""
    }

    fun log(s: String) {
        Log.d(">>>>", s)
    }
}